package com.ruoyi.walmart.thread;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.walmart.domain.auth.ShopAuth;
import com.ruoyi.walmart.domain.order.*;
import com.ruoyi.walmart.util.walmartUtil;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

public class OrderProcessingTask implements Runnable {

    private ShopAuth shopAuth;
    private  List<AllOrder>  orderList;
    private List<OrderItem> orderItemList;
    private List<OrderCharge> orderChargeList;
    private Date orderDate;

    public OrderProcessingTask(ShopAuth shopAuth, List<AllOrder> orderList, List<OrderItem> orderItemList, List<OrderCharge> orderChargeList, Date orderDate) {
        this.shopAuth = shopAuth;
        this.orderList = orderList;
        this.orderItemList = orderItemList;
        this.orderChargeList = orderChargeList;
        this.orderDate = orderDate;
    }

    @Override
    public void run() {
        Meta meta = new Meta();
        String nextCursor = "*";
        while (nextCursor != null) {
            meta.setNextCursor(nextCursor);
            if(orderDate != null){
                String createdStartDate = convertToUTC(orderDate);//DateUtil.format(orderDate, "yyyy-MM-dd'T'HH:mm:ss'Z'");
                meta.setCreatedStartDate(createdStartDate);
            }
            JSONObject jsonObject = walmartUtil.listOrdersUs(meta, shopAuth);
            System.out.println(jsonObject);
            if (jsonObject == null) {
                break;
            }
            if (jsonObject.getJSONObject("list").getJSONObject("meta").getInteger("totalCount") != 0) {
                JSONArray array = jsonObject.getJSONObject("list").getJSONObject("elements").getJSONArray("order");
                for (Object o : array) {
                    JSONObject orderLines = (JSONObject) o;
                    String jsonOrderLines = orderLines.toString();
                    Order order = JSON.parseObject(jsonOrderLines, Order.class);
                    AllOrder allOrder = new AllOrder();
                    allOrder.setPurchaseOrderId(order.getPurchaseOrderId());
                    allOrder.setCustomerOrderId(order.getCustomerOrderId());
                    allOrder.setCustomerEmailId(order.getCustomerEmailId());
                    allOrder.setOrderType(order.getOrderType());
                    allOrder.setOrderDate(getDate(order.getOrderDate()));
                    allOrder.setPhone(order.getShippingInfo().getPhone());
                    allOrder.setEstimatedDeliveryDate(getDate(order.getShippingInfo().getEstimatedDeliveryDate()));
                    allOrder.setEstimatedShipDate(getDate(order.getShippingInfo().getEstimatedShipDate()));
                    allOrder.setName(order.getShippingInfo().getPostalAddress().getName());
                    allOrder.setAddress1(order.getShippingInfo().getPostalAddress().getAddress1());
                    allOrder.setAddress2(order.getShippingInfo().getPostalAddress().getAddress2());
                    allOrder.setCity(order.getShippingInfo().getPostalAddress().getCity());
                    allOrder.setState(order.getShippingInfo().getPostalAddress().getState());
                    allOrder.setPostalCode(order.getShippingInfo().getPostalAddress().getPostalCode());
                    allOrder.setCountry(order.getShippingInfo().getPostalAddress().getCountry());
                    allOrder.setAddressType(order.getShippingInfo().getPostalAddress().getAddressType());
                    allOrder.setAuthId(shopAuth.getAuthId());
                    allOrder.setShipNode(order.getShipNode().getType());
                    List<Order.OrderLine> orderLine = order.getOrderLines().getOrderLine();
                    for (Order.OrderLine orders : orderLine) {
                        OrderItem orderItem = new OrderItem();
                        orderItem.setPurchaseOrderId(order.getPurchaseOrderId());
                        orderItem.setCustomerOrderId(order.getCustomerOrderId());
                        orderItem.setProductName(orders.getItem().getProductName());
                        orderItem.setSku(orders.getItem().getSku());
                        orderItem.setAuthId(shopAuth.getAuthId());
                        List<Order.OrderLineStatus> orderLineStatus = orders.getOrderLineStatuses().getOrderLineStatus();
                        for (Order.OrderLineStatus lineStatus: orderLineStatus) {
                            orderItem.setStatus(lineStatus.getStatus());
                        }
                        orderItem.setFulfillmentOption(orders.getFulfillment().getFulfillmentOption());
                        orderItem.setShipMethod(orders.getFulfillment().getShipMethod());
                        orderItem.setShippingProgramType(orders.getFulfillment().getShippingProgramType());
                        orderItemList.add(orderItem);
                        List<Order.Charge> charge = orders.getCharges().getCharge();
                        for (Order.Charge newCharge: charge) {
                            OrderCharge orderCharge = new OrderCharge();
                            orderCharge.setPurchaseOrderId(order.getPurchaseOrderId());
                            orderCharge.setCustomerOrderId(order.getCustomerOrderId());
                            orderCharge.setChargeType(newCharge.getChargeType());
                            orderCharge.setChargeName(newCharge.getChargeName());
                            orderCharge.setChargeCurrency(newCharge.getChargeAmount().getCurrency());
                            BigDecimal chargeAmount = new BigDecimal(newCharge.getChargeAmount().getAmount());
                            orderCharge.setChargeAmount(chargeAmount);
                            if(newCharge.getTax() == null || newCharge.getTax().equals("")){
                                orderCharge.setTaxName(null);
                                orderCharge.setTaxCurrency(null);
                                orderCharge.setTaxAmount(null);
                                orderChargeList.add(orderCharge);
                            }else {
                                orderCharge.setTaxName(newCharge.getTax().getTaxName());
                                orderCharge.setTaxCurrency(newCharge.getTax().getTaxAmount().getCurrency());
                                BigDecimal taxAmount = new BigDecimal(newCharge.getTax().getTaxAmount().getAmount());
                                orderCharge.setTaxAmount(taxAmount);
                                orderChargeList.add(orderCharge);
                            }

                        }
                    }
                    orderList.add(allOrder);
                }
            }
            nextCursor = jsonObject.getJSONObject("list").getJSONObject("meta").getString("nextCursor");
        }
    }


    private static Date getDate(long timestamp){
        // tiestamp = 1711495795316
        long time = timestamp / 1000; // 将毫秒转换为秒
        // 从时间戳创建 Instant 对象
        Instant instant = Instant.ofEpochSecond(time);
        // 指定目标时区
        ZoneId zoneId = ZoneId.of("America/Los_Angeles"); // 选择你需要的时区
        // 将 Instant 对象转换为指定时区的 ZonedDateTime
        ZonedDateTime zonedDateTime = instant.atZone(zoneId);
        LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        return date;
    }

    /**
     * 将美西时间转换为 UTC 时间，并格式化为 API 要求的格式（yyyy-MM-dd'T'HH:mm:ss'Z'）
     *
     * @param orderDate 美西时间（java.util.Date 类型）
     * @return 转换后的 UTC 时间字符串（格式：yyyy-MM-dd'T'HH:mm:ss'Z'）
     */
    public static String convertToUTC(Date orderDate) {
        if (orderDate == null) {
            return null;
        }

        // 当前时间已经是太平洋时间了
        ZonedDateTime pacificDateTime = orderDate.toInstant()
                .atZone(ZoneId.systemDefault()); // 使用系统默认时区
        // 判断当前时间是否处于夏令时（PDT），若是则加 7 小时，否则加 8 小时（PST）
        ZonedDateTime _pacificDateTime = orderDate.toInstant()
                .atZone(ZoneId.of("America/Los_Angeles")); // 使用系统默认时区
        int hoursToAdd = _pacificDateTime.getZone().getRules().isDaylightSavings(pacificDateTime.toInstant()) ? 7 : 8;

        // 动态加上 7 或 8 小时
        pacificDateTime = pacificDateTime.plusHours(hoursToAdd);

        //让沃尔玛查询往前俩个小时（共3小时前）查询数据，本地删除一个小时前的数据
        pacificDateTime = pacificDateTime.minusHours(2);

        // 格式化为符合沃尔玛 API 要求的 ISO 8601 格式（yyyy-MM-dd'T'HH:mm:ss'Z'）
        DateTimeFormatter isoFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
        return isoFormatter.format(pacificDateTime);
    }
}